package com.penngo.gui.dfdiff.utils;

import antlr.StringUtils;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;


public class Adler32Utils {

    public static boolean stopCheckFile = false;



    public static String getAdler32(File file) {
        String adler32 = null;
        String ext =  FileUtil.getSuffix(file);
        if(ext != null){
            ext = ext.toLowerCase();
        }
        String resource = ",zip,rar,7z,png,gif,jpg,jpeg,gif,ico,avi,mp3,wma,wav,mp4,mkv,rmvb,pdf,aif,arj,exe,bmp,doc,docx,xls,xlsx,ppt,pptx,woff,wps,dps,et,ttf,eot,ds_store,bfc,";
        if(resource.indexOf(ext) == -1){
            String str = ToolUtil.readString(file);
            if(str != null){
                // 处理不同平台换行不一样的情况
                str = str.replace("\r\n", "\n");
                str = str.replace("\r", "\n");
                adler32 = getAdler32(str);
            }
            else{
                adler32 = getFileAdler32(file);
            }
        }
        else{
            adler32 = getFileAdler32(file);
        }
        return adler32;
    }

    public static String getFileAdler32(File file) {
        CheckedInputStream cis = null;
        long checksum = 0;
        try {
            cis = new CheckedInputStream(new FileInputStream(file), new Adler32());
            byte[] buf = new byte[4096];
            while(cis.read(buf) >= 0 && !stopCheckFile) {
            }
            checksum = cis.getChecksum().getValue();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try{
                cis.close();
            }catch(Exception e)
            {
                e.printStackTrace();
            }
        }

        if(stopCheckFile)
        {
            System.out.println("getAdler32 has to be stop ----------------------");
        }
        if(checksum == 0)
        {
            return "";
        }
        return String.valueOf(checksum);
    }
    public static String getAdler32(String str) {

    	CheckedInputStream cis = null;
        try {
            cis = new CheckedInputStream(new ByteArrayInputStream(str.getBytes()), new Adler32());

            byte[] buf = new byte[1024];
            while(cis.read(buf) >= 0) {
            }

            long checksum = cis.getChecksum().getValue();
            
            return String.valueOf(checksum);

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
        	try{
        		cis.close();
        	}catch(Exception e)
        	{
        		e.printStackTrace();
        	}
        }

        return "";
    }

}

